/*
 * @Author: Caoping
 * @Date: 2021-02-22 09:30
 * @Last Modified by: CaoPing
 * @Last Modified time: 2021-02-22 09:30
 */
import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import ToolBar from '@components/ToolBar';
import ComponentsList from '@components/ComponentsList';
import Editor from '@components/Editor';
import AttrList from '@components/AttrList';
import componentList from '@components/custom-components/component-list';
import { deepCopy } from '@utils/index';
import "./index.scss";
import { setCurrComp, setComponent, setIsClickComponent, setMenuShow } from '@/store/actions/visualdrag';

const Pages = ({ componentData, isClickComponent, canvasStyleData, dispatch }) => {

  const handleDrop = (e) => {
    e.preventDefault()
    e.stopPropagation()
    const component = deepCopy(componentList[e.dataTransfer.getData('index')])
    component.style.top = e.nativeEvent.offsetY;
    component.style.left = e.nativeEvent.offsetX;
    component.id = componentData.length;
    let data = [...componentData];
    data.push(component);
    dispatch(setComponent(data))
  }

  const handleDragOver = (e) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
  }

  const handleMouseDown = () => {
    dispatch(setIsClickComponent(false))
  };

  const deselectCurComponent = () => {
    if (!isClickComponent) {
      let data = {
        index: null,
        component: null
      };
      dispatch(setCurrComp(data))
    }
    dispatch(setMenuShow(false));
  }

  return (
    <div className="baseContent visualdrag-page">
      {/* 工具栏 */}
      <ToolBar />
      <div className="con-wrap">
        {/* 左侧组件列表 */}
        <section className="left">
          <ComponentsList />
        </section>
        {/* 中间画布 */}
        <section className="center">
          <div className="content"
            style={{
              width: canvasStyleData.width + 'px',
              height: canvasStyleData.height + 'px'
            }}
            onDrop={(e) => handleDrop(e)}
            onDragOver={(e) => handleDragOver(e)}
            onMouseDown={() => handleMouseDown()}
            onMouseUp={() => deselectCurComponent()}>
            <Editor />
          </div>
        </section>
        {/* 右侧属性列表 */}
        <section className="right">
          <AttrList />
        </section>
      </div>
    </div>
  );
};

const mapStateToProps = (state) => {
  return {
    ...state.VisualDrag,
  };
};

export default connect(mapStateToProps)(Pages);
